<template>
    <div class="wrap">
        <template v-for="(item, index) in formData" :key="index">
            <FromItem ref="childValid" :formData="item" :rules="rules">
                <template v-if="index === 0">
                    <h1>主体角色</h1>
                </template>
                <template v-else>
                    <h1>连体角色{{ index }}</h1>
                    <el-button type="primary" @click="onDeleteForm(index)" size="large">删除</el-button>
                </template>
            </FromItem>
        </template>
        <el-button type="primary" @click="onAddForm" size="large">添加连体角色</el-button>
        <el-button type="primary" @click="onSubmit" size="large">提交</el-button>

    </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import axios from 'axios';
import { setChilren } from '@/utils/setChildren'
import FromItem from '@/components/FromItem.vue';

const formData = ref([])
const rules = ref(null)
const childValid = ref([])

const data = ref({
    data: {
        role: []
    }
})
const onSubmit = () => {
    data.value.data.role = []
    childValid.value.forEach(async item => {
        if (item.formValid) {
            const isVaild = await item.formValid()
            if (isVaild) {
                data.value.data.role.push(item.form)
                console.log('数据提交：', JSON.stringify(data.value))
            }
        }
    })
}
const onAddForm = () => {
    formData.value.push(formData.value[0])
}

const onDeleteForm = (index) => {
    formData.value.splice(index, 1)
    data.value.data.role.splice(index, 1)
}

// 加载JSON数据
onMounted(async () => {
    try {
        const response = await axios.get('/api/form/53da6912.json'); // 跨域代理
        const data = response.data.role
        const newData = setChilren(data)

        rules.value = newData.reduce((acc, item) => {
            if (item.validate) {
                acc[item.game_field_id] = item.validate;
                acc[item.game_field_id].message = item.validate.errorMessage || '请选择参数';
            }
            return acc;
        }, {})
        formData.value.push(newData)

    } catch (error) {
        console.error(error);
    }
});

</script>

<style scoped>
.wrap {
    padding: 40px;
}
</style>
